package com.keyinong.caizhengting.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.ImageUtilsLoaderFile;
import com.keyinong.caizhengting.entity.AppAdsBean;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-3-20 下午3:47:52
 * @类名：AdViewPagerAdapter.java
 * @功能: 首页幻灯片适配器
 */

public class AdViewPagerAdapter extends PagerAdapter {
    Context context;
    ArrayList<View> list;
    ArrayList<AppAdsBean> adlist;

    public AdViewPagerAdapter(Context context, ArrayList<View> list,
                              ArrayList<AppAdsBean> adlist) {
        super();
        this.context = context;
        this.list = list;
        this.adlist = adlist;
    }

    @Override
    public int getCount() {
        if (adlist != null) {
            return adlist.size();
        }
        return 0;
    }

    // 断是否由对象生成界面
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0 == arg1;
    }

    // 是从ViewGroup中移出当前View
    @Override
    public void destroyItem(View container, int position, Object object) {
        // ((ViewPager) container).removeView(list.get(position));

        // ((ViewPager)container).removeView(mImageViews[position%mImageViews.length]);

        int newPosition = position % list.size();
        ((ViewPager) container).removeView(list.get(newPosition));
    }

    // 返回一个对象，这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
    @Override
    public Object instantiateItem(final View container, final int position) {
        // ((ViewPager)container).addView(list.get(position));
        // return list.get(position);

        // try{
        // ((ViewPager)container).addView(mImageViews[position%mImageViews.length],0);
        // }catch(Exception e){
        //
        // }
        // return mImageViews[position%mImageViews.length];
        // int newPosition=position%list.size();

        // ((ViewPager)container).addView(list.get(position));
        // return list.get(position);

        String imgurl = adlist.get(position).getImg_url();
        if (!"".equals("imgurl") || imgurl != null) {
            View view = list.get(position);
            ImageView image = ((ImageView) view.findViewById(R.id.img_ad));
            // image.setBackground(cachedImage);
            ImageUtilsLoaderFile.displayImage(context, adlist.get(position)
                    .getImg_url(), image, R.drawable.img_vp_a);

            ((ViewPager) container).removeView(list.get(position));
            ((ViewGroup) container).addView(list.get(position));
        }
        return list.get(position);

    }
}
